import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('@/views/layout/home.vue')
        },
        {
          path: '/category',
          name: 'category',
          component: () => import('@/views/layout/category.vue')
        },
        {
          path: '/cart',
          name: 'cart',
          component: () => import('@/views/layout/cart.vue')
        },
        {
          path: '/user',
          name: 'user',
          component: () => import('@/views/layout/user.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login')
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('@/views/search')
    },
    {
      path: '/searchList',
      name: 'searchList',
      component: () => import('@/views/search/list.vue')
    },
    {
      path: '/prodetail/:id',
      name: 'prodetail',
      component: () => import('@/views/prodetail')
    },
    {
      path: '/pay',
      name: 'pay',
      component: () => import('@/views/pay')
    },
    {
      path: '/myorder',
      name: 'myorder',
      component: () => import('@/views/myorder')
    }
  ]
})
const authList = ['/pay', 'myorder']
/**
 * 全局路由守卫
 * @param to 到哪里去，完整的路由信息(路径， 参数)
 * @param from 从哪里来， 完整的路由信息(路径， 参数)
 * @param next 是否放行
 *  - next() 直接放行
 *  - next(path) 进行拦截， 跳转到指定的path
 */
router.beforeEach((to, from, next) => {
  if (!authList.includes(to.path)) {
    next()
    return
  }
  // 1. 获取token
  const token = store.getters.token
  // 2. 判断是否登录
  if (to.path === '/login') {
    next()
  } else {
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
